package com.kungfuhacking.wristbandpro.location;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.maps.TextureMapView;
import com.kungfuhacking.wristbandpro.R;
import com.kungfuhacking.wristbandpro.base.view.BaseFragment;
import com.kungfuhacking.wristbandpro.custom.TitleBarView;
import com.kungfuhacking.wristbandpro.location.activity.AddSNCodeActivity;
import com.kungfuhacking.wristbandpro.location.activity.AffectionActivity;
import com.kungfuhacking.wristbandpro.location.activity.HistoryActivity;
import com.kungfuhacking.wristbandpro.location.activity.PickOldActivity;
import com.kungfuhacking.wristbandpro.location.activity.SafeAreaListActivity;
import com.kungfuhacking.wristbandpro.location.activity.ShareActivity;
import com.kungfuhacking.wristbandpro.location.presenter.ILocationPresenter;
import com.kungfuhacking.wristbandpro.location.view.ILocationView;
import com.kungfuhacking.wristbandpro.utils.Constant;
import com.kungfuhacking.wristbandpro.utils.LogUtil;
import com.kungfuhacking.wristbandpro.widget.BatteryView;



/**
 * 定位fragment
 * Created by Aaron on 17/3/30.
 */

public class FragmentOne extends BaseFragment implements View.OnClickListener, ILocationView {

    private String TAG = getClass().getSimpleName();
    private TextureMapView mapView;
    private ILocationPresenter iLocationPresenter = new ILocationPresenter(this);
    //    private IHomePresenter iHomePresenter = new IHomePresenter(this);
    private AMapLocationClient mLocationClient;
    private TitleBarView titlebar;
    private RelativeLayout rl_no_baby;
    private TextView tv_add;
    private LinearLayout ll_location;
    private TextView tv_name;
    private TextView tv_location;
    private TextView tv_battery;
    private BatteryView bv;
    private ImageView iv_location_type;
    private TextView tv_location_type;
    private ImageView iv_status;
    private TextView tv_status;
    private ProgressDialog settingDialog;
    private ProgressDialog unbindDialog;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        LogUtil.e(TAG, "==onCreateView==");
        View view = inflater.inflate(R.layout.fragment_one, null);

        initView(view);
        initMap(savedInstanceState, view);

        return view;

    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();

        iLocationPresenter.needShowLocationErr = true;//选择该手表后的第一次定位
        iLocationPresenter.needMoveToLocation = true;//选择该手表后的第一次定位
        //设置老人姓名
        titlebar.setTitle(sp.getString(Constant.CURRENTOLDNAME, ""));
        iLocationPresenter.stopLoopLcation();//停止之前的轮询定位
        iLocationPresenter.getLocationInfo();//开始新的轮询定位
    }

    private void initMap(Bundle savedInstanceState, View view) {
        mapView = (TextureMapView) view.findViewById(R.id.gdmap);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        mLocationClient = new AMapLocationClient(getActivity());
        iLocationPresenter.initMap(mapView.getMap(), mLocationClient);
    }

    private void initView(View view) {

        rl_no_baby = (RelativeLayout) view.findViewById(R.id.rl_no_baby);
        tv_add = (TextView) view.findViewById(R.id.tv_add);
        ll_location = (LinearLayout) view.findViewById(R.id.ll_location);
        ImageView iv_location = (ImageView) view.findViewById(R.id.iv_location);
        ImageView iv_call = (ImageView) view.findViewById(R.id.iv_call);
        ImageView iv_history = (ImageView) view.findViewById(R.id.iv_history);
        ImageView iv_share = (ImageView) view.findViewById(R.id.iv_share);

        tv_name = (TextView) view.findViewById(R.id.tv_name);
        tv_location = (TextView) view.findViewById(R.id.tv_location);
        tv_battery = (TextView) view.findViewById(R.id.tv_battery);
        bv = (BatteryView) view.findViewById(R.id.bv);
        iv_location_type = (ImageView) view.findViewById(R.id.iv_location_type);
        tv_location_type = (TextView) view.findViewById(R.id.tv_location_type);
        iv_status = (ImageView) view.findViewById(R.id.iv_status);
        tv_status = (TextView) view.findViewById(R.id.tv_status);

        titlebar = (TitleBarView) view.findViewById(R.id.titlebar);
        titlebar.setOnRightClickListener(this);
        titlebar.setOnLeftClickListener(this);

        iv_location.setOnClickListener(this);
        iv_call.setOnClickListener(this);
        iv_history.setOnClickListener(this);
        iv_share.setOnClickListener(this);
        tv_add.setOnClickListener(this);
    }

    @Override
    public void showWristbandSetting() {

        settingDialog = new ProgressDialog(getActivity());
        settingDialog.setCanceledOnTouchOutside(true);
        settingDialog.setCancelable(true);
        settingDialog.show();
        settingDialog.setContentView(R.layout.dialog_wristband_setting);

        TextView tv_safe_area = (TextView) settingDialog.findViewById(R.id.tv_safe_area);
        TextView tv_white_list = (TextView) settingDialog.findViewById(R.id.tv_white_list);
        TextView tv_state = (TextView) settingDialog.findViewById(R.id.tv_state);
        TextView tv_unbind = (TextView) settingDialog.findViewById(R.id.tv_unbind);
        TextView tv_find_watch = (TextView) settingDialog.findViewById(R.id.tv_find_watch);

        tv_safe_area.setOnClickListener(this);
        tv_white_list.setOnClickListener(this);
        tv_state.setOnClickListener(this);
        tv_unbind.setOnClickListener(this);
        tv_find_watch.setOnClickListener(this);
    }

    private void hideSettingDialog() {
        if (settingDialog != null && settingDialog.isShowing())
            settingDialog.dismiss();
    }

    /**
     * 没有权限的页面
     */
    @Override
    public void pageNoPermission() {
        tv_add.setVisibility(View.GONE);//添加手表的按钮消失
        rl_no_baby.setVisibility(View.VISIBLE);
        ll_location.setVisibility(View.INVISIBLE);
        titlebar.setLeftImage(null);
    }

    /**
     * 有权限 有sn码  正常定位
     */
    @Override
    public void pageWithPermissionAndSN() {
        rl_no_baby.setVisibility(View.INVISIBLE);
        ll_location.setVisibility(View.VISIBLE);
        titlebar.setLeftImage(getResources().getDrawable(R.mipmap.ic_watch_setting));
        titlebar.setOnLeftClickListener(this);
    }

    /**
     * 有权限但是没有sn码
     */
    @Override
    public void pageWithPermissionNoSN() {
        rl_no_baby.setVisibility(View.VISIBLE);
        ll_location.setVisibility(View.INVISIBLE);
        tv_add.setVisibility(View.VISIBLE);
        titlebar.setLeftImage(null);
        titlebar.setOnLeftClickListener(null);
    }

    /**
     * 没有权限的页面
     */
    @Override
    public void pageWithPermission() {
        rl_no_baby.setVisibility(View.INVISIBLE);
        ll_location.setVisibility(View.VISIBLE);
        titlebar.setLeftImage(getResources().getDrawable(R.mipmap.ic_watch_setting));
        titlebar.setOnLeftClickListener(this);
    }

    /**
     * 定位出差
     */
    public void locationErr() {
        rl_no_baby.setVisibility(View.VISIBLE);
        ll_location.setVisibility(View.INVISIBLE);
        titlebar.setLeftImage(null);
        titlebar.setOnLeftClickListener(null);
        tv_add.setVisibility(View.GONE);
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
//        deactivate();
//        LogUtil.e(TAG, " ==== onpause ==== ");
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 停止定位
     */
    public void deactivate() {
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        mapView.onDestroy();

        if (null != mLocationClient)
            mLocationClient.onDestroy();

        iLocationPresenter.stopLoopLcation();//停止之前的轮询定位
        iLocationPresenter.clearRequest();
    }

    @Override
    public void setTitleName(String oldName) {
        titlebar.setTitle(oldName);
    }

    @Override
    public void setLocationName(String info) {
        tv_name.setText(info);
    }

    @Override
    public void setLocationAddress(String address) {
        tv_location.setText(address);
    }

    @Override
    public void setLocationBatteryView(String batteryView) {

        tv_battery.setText(batteryView + "%");
        int currentBattery;
        if (TextUtils.isEmpty(batteryView))
            currentBattery = 0;
        else
            currentBattery = Integer.parseInt(batteryView);
        bv.setLength(28, 12, 5, 10, 1);
        if (currentBattery <= 20) //电量小于20变红
            bv.setColor(Color.BLACK, Color.RED);
        else  //大于20是绿的
            bv.setColor(Color.BLACK, Color.GREEN);

//        if (currentBattery <= 5)
//            bv.setPower(5);
//        else
        bv.setPower((currentBattery <= 5) ? 5 : currentBattery);

    }

    @Override
    public void setLocationType(String locationType) {

        if (TextUtils.isEmpty(locationType)) {
            tv_location_type.setText("暂无定位");
            return;
        }

        switch (locationType) {

            case "gsm":
                tv_location_type.setText("基站定位");
                iv_location_type.setImageResource(R.mipmap.ic_location_station);
                break;
            case "gps":
                tv_location_type.setText("GPS定位");
                iv_location_type.setImageResource(R.mipmap.ic_location_gps);
                break;
            case "wifi":
                tv_location_type.setText("WIFI定位");
                iv_location_type.setImageResource(R.mipmap.ic_location_wifi);
                break;
            default:
                tv_location_type.setText("暂无定位");
                break;
        }

    }

    @Override
    public void setIsOnline(boolean isOnline) {
        tv_status.setText(isOnline ? "在线" : "离线");
    }

    @Override
    public void setIsOnlinePic(int sign) {
        if (sign == 0) {
            iv_status.setImageResource(R.mipmap.ic_signal_zero);
        } else if (sign <= 20) {
            iv_status.setImageResource(R.mipmap.ic_signal_twenty);
        } else if (sign <= 40) {
            iv_status.setImageResource(R.mipmap.ic_signal_fourty);
        } else if (sign <= 60) {
            iv_status.setImageResource(R.mipmap.ic_signal_sixty);
        } else if (sign <= 99) {
            iv_status.setImageResource(R.mipmap.ic_signal_eighty);
        } else if (sign == 100) {
            iv_status.setImageResource(R.mipmap.ic_signal_full);
        }
    }

    private TextView infoView;


    /**
     * 点击底部导航栏 重新定位
     */
    public void reBottonLocation() {
        Log.d(TAG, "   ==== 点击底部定位模块 重新定位 ====   ");
        iLocationPresenter.reBottonLocation();
    }

    @Override
    public Bitmap getMarketBitmap() {
        return BitmapFactory.decodeResource(getResources(), R.mipmap.ic_thumb);
    }

    public View getMarkerView(String oldName) {
        if (infoView == null) {
            infoView = new TextView(getActivity());
            infoView.setGravity(Gravity.CENTER);
            infoView.setTextSize(15);
            infoView.setBackgroundResource(R.mipmap.ic_mylocation_bg);
        }
        infoView.setText(oldName);
        return infoView;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.iv_left://手表设置
                showWristbandSetting();
                break;

            case R.id.iv_right://切换老人
                nextActivity(PickOldActivity.class);
                break;

            case R.id.iv_location://定位 请求gps定位
                iLocationPresenter.reLocation();
                break;

            case R.id.iv_share://分享

                if (TextUtils.isEmpty(sp.getString(Constant.CURRENTOLDID, ""))) {
                    showErr("请先选择老人");
                    return;
                }
                nextActivity(ShareActivity.class);

                break;

            case R.id.tv_add://添加SN码
                nextActivity(AddSNCodeActivity.class);
                break;

            case R.id.iv_call://拨打电话
                iLocationPresenter.callOld(new AlertDialog.Builder(getActivity()));
                break;

            case R.id.iv_history://历史轨迹
                nextActivity(HistoryActivity.class);
                break;

            case R.id.tv_safe_area://安全区域
                hideSettingDialog();
                nextActivity(SafeAreaListActivity.class);
                break;

            case R.id.tv_white_list://亲情号码

                if (TextUtils.isEmpty(sp.getString(Constant.CURRENTOLDID, ""))) {
                    showErr("请先绑定或选择老人");
                    return;
                }
                hideSettingDialog();
                nextActivity(AffectionActivity.class);

                break;

            case R.id.tv_state://手表设置
                hideSettingDialog();
                iLocationPresenter.settingActiviyt();
                break;

            case R.id.tv_unbind://解绑手表

                if (TextUtils.isEmpty(sp.getString(Constant.CURRENTOLDID, ""))) {
                    showErr("请先绑定或选择老人");
                    return;
                }

                hideSettingDialog();
                showUnwrapWatchDialog();

                break;

            case R.id.tv_find_watch://查找手表
                hideSettingDialog();
                iLocationPresenter.findWatch();
                break;

            case R.id.tv_cancel:
                dimissUnbind();
                break;

            case R.id.tv_confirm://解绑手表
                dimissUnbind();
                iLocationPresenter.unwrapWatch();
                break;

        }
    }

    private void dimissUnbind() {
        if (unbindDialog != null && unbindDialog.isShowing()) {
            unbindDialog.dismiss();
        }
    }

    /**
     * 弹出提示解除绑定手表的对话框
     */
    private void showUnwrapWatchDialog() {

        unbindDialog = new ProgressDialog(getActivity());
        unbindDialog.setCanceledOnTouchOutside(true);
        unbindDialog.show();
        unbindDialog.setContentView(R.layout.item_show_remind);
        TextView tv_confirm = (TextView) unbindDialog.findViewById(R.id.tv_confirm);
        TextView tv_cancel = (TextView) unbindDialog.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(this);
        tv_confirm.setOnClickListener(this);

    }

}
